<?php

/**
 * Created by muniao.
 * User: muniao
 * Date: 2018/8/2
 * Time: 13:20
 */

namespace app\api\controller\android\v13;


use app\api\model\Aliyunoss;
use app\api\model\Capital;
use app\api\model\PollingModel;
use app\index\model\Pdf;
use think\Controller;
use  app\api\model\Approval;
use app\api\model\Authority;
use app\api\model\Common;
use think\Db;
use think\Exception;
use think\Request;

class Visa extends Controller
{
    protected $model;
    protected $us;
    protected $newTime;
    protected $endTime;
    protected $overtime;
    protected $pdf;

    public function _initialize()
    {

        $this->model = new Authority();

        $this->us = Authority::check(1);
    }

    public function Applets()
    {
        $data = Request::instance()->post();
        if (empty($data['id'])) {
            db('visa_form')->insertGetId([
                'visa_map' => '',
                'creation_time' => time(),
                'capital_id' => '',
                'autograph' => '',
                'order_id' => $data['order_id'],
                'title' => '增项减项签证单',
            ]);
        } else {
            db('visa_form')->where('id', $data['id'])->update(['share' => 1]);
        }

        r_date([], 200, '新增成功');
    }

    public function SignUp()
    {
        $data = Request::instance()->post();
        db()->startTrans();
        try {
            $pdf = (new Pdf())->shi($data['order_id']);
            if ($pdf) {
                $textDefault  = [];
                $background   = ROOT_PATHS . '/uploads/PDF/' . $data['order_id'] . '.png'; //背景
                $img          = imagecreatefrompng($background);
                $img_info     = imagesy($img);
                $imageDefault = [
                    'left' => 120,
                    'top' => $img_info - 170,
                    'right' => 0,
                    'bottom' => 0,
                    'width' => 100,
                    'height' => 100,
                    'opacity' => 50,
                ];
                if (file_exists($background)) {
                    if (!empty($data['autograph']) && (parse_url($data['autograph'])['host'] == 'imgaes.yiniaoweb.com' || parse_url($data['autograph'])['host'] == 'api.yiniaoweb.com')) {
                        $path = '/app/' . (new PollingModel())->file_exists_S3($data['autograph'], ROOT_PATH . 'public/app/');
                    } else {
                        $path = parse_url($data['autograph'], PHP_URL_PATH);
                    }
                    $config['image'][]['url'] = ROOT_PATHS . $path;
                    $filename                 = ROOT_PATHS . '/ContractNumber/' . $data['order_id'] . '.jpg';
                    Common::getbgqrcode($imageDefault, $textDefault, $background, $filename, $config);

                    $ali = new Aliyunoss();
                    if (file_exists($filename)) {
                        $oss_result = $ali->upload('contract/' . config('city') . '/' . $data['order_id'] . time() . '.jpg', $filename);
                        if ($oss_result['info']['http_code'] == 200) {
                            $path = parse_url($oss_result['info']['url'])['path'];
                            if (empty($data['id'])) {
                                db('visa_form')->insertGetId([
                                    'visa_map' => 'https://images.yiniao.co' . $path,
                                    'creation_time' => time(),
                                    'signing_time' => time(),
                                    'capital_id' => implode(',', $pdf['capital_id']),
                                    'autograph' => $data['autograph'],
                                    'order_id' => $data['order_id'],
                                    'title' => '增项减项签证单',
                                ]);
                            } else {
                                db('visa_form')->where('id', $data['id'])->update([
                                    'visa_map' => 'https://images.yiniao.co' . $path,
                                    'capital_id' => implode(',', $pdf['capital_id']),
                                    'autograph' => $data['autograph'],
                                    'signing_time' => time(),
                                ]);
                            }

                            db('capital')->whereIn('capital_id', $pdf['capital_id'])->update([
                                'signed' => 1,
                            ]);

                            if (file_exists($filename)) {
                                unlink($filename);
                            };
                            if (file_exists($config['image'][0]['url'])) {
                                unlink($config['image'][0]['url']);
                            }
                        }
                    }
                    db()->commit();
                    r_date([], 200, '新增成功');
                }
            }
        } catch (\Exception $e) {
            db()->rollback();
            r_date([], 300, $e->getMessage());
        }
    }

    /*
     * 列表
     */
    public function VisaList()
    {
        $data = Request::instance()->post();

        $orderList    = db('order')
            ->field('if(order_setting.visa_form_confirm=1,0,1) as isNeedPaper,order.created_time')
            ->join('order_setting', 'order.order_id=order_setting.order_id', 'left')
            ->where('order.order_id', $data['order_id'])
            ->find();
        $created_time = $orderList['created_time'];
        $visa_form    = db('visa_form')->where('order_id', $data['order_id'])->field('id,title,signing_time,capital_id,visa_map,money,mainMoney,give_money,purchasin_money,sign_money')->select();
        // if ($created_time > 1660150844 && $orderList['isNeedPaper'] == 0) {
        //     $visa_form = db('visa_form')->where('order_id', $data['order_id'])->whereNotNull('signing_time')->field('id,title,signing_time,capital_id,visa_map,money,mainMoney,give_money,purchasin_money,sign_money')->select();
        // }
        foreach ($visa_form as $k => $o) {
            $capital = db('capital')->where('capital.enable', 1)->whereIn('capital_id', $o['capital_id'])->select();
            $money   = 0;
            $moneys  = 0;
            foreach ($capital as $item) {

                $capital = Db::query("select * from visa_form where FIND_IN_SET('" . $item['capital_id'] . "',capital_id) ");
                if (!empty($o['signing_time']) && $item['increment'] == 1 && $o['signing_time'] < $item['untime'] && $item['give'] == 0) {
                    $money += $item['to_price'];
                }
                if ($item['types'] == 2 && $item['increment'] != 1 && $item['up_products'] != 1 && $item['give'] == 0) {

                    $money -= $item['to_price'];
                }
                if (!empty($o['signing_time']) && $item['increment'] == 1 && $item['untime'] != 0 && $o['signing_time'] > $item['untime'] && count($capital) > 1) {

                    $money -= $item['to_price'];
                }


                if ($item['increment'] == 1 && $item['types'] == 1 && $item['give'] == 0) {

                    $money += $item['to_price'];
                }
                if ($item['up_products'] == 1 && $item['give'] == 0) {

                    $money -= $item['to_price'];
                }
                if ($item['products'] == 1) {

                    $moneys += $item['to_price'];
                }
            }

            $visa_form[$k]['creation_time'] = empty($o['signing_time']) ? '' : date('Y-m-d H:i:s', $o['signing_time']);
            $visa_form[$k]['isNeedPaper']   = $orderList['isNeedPaper'];
            $visa_form[$k]['shell']         = $orderList['isNeedPaper'];
            $visa_form[$k]['money']         = 0;
            //            $visa_form[$k]['money']         = round($money + $o['money'] + $o['mainMoney'] - $o['give_money'] - $o['purchasin_money'] + $moneys, 2);
            if ($o['sign_money'] != 0) {

                $visa_form[$k]['money'] = $o['sign_money'];
            }
        }

        r_date($visa_form, 200);
    }

    /*
    * 列表
    */
    public function VisaInfo()
    {
        $parem                 = Request::instance()->post();
        $visa_form             = db('visa_form')->where('id', $parem['id'])->find();
        $mainMoney             = empty($visa_form['mainMoney']) ? 0 : $visa_form['mainMoney'];
        $give_money            = empty($visa_form['give_money']) ? 0 : $visa_form['give_money'];
        $purchasin_money       = empty($visa_form['purchasin_money']) ? 0 : $visa_form['purchasin_money'];
        $money                 = empty($visa_form['money']) ? 0 : $visa_form['money'];
        $id                    = empty($visa_form['id']) ? 0 : $visa_form['id'];
        $duration              = empty($visa_form['duration']) ? 0 : $visa_form['duration'];
        $list                  = db('capital')->whereIn('capital_id', $visa_form['capital_id'])
            ->where(function ($query) {
                $query->where('types=2')->whereOr('increment=1')->whereOr('approve=4')->whereOr('approve=5')->whereOr('up_products=1');
            })
            ->field('projectId,capital_id,class_a,class_b,company,square,un_Price,zhi,to_price,fen,capital.give as giveType,increment,types,agency,signed,cooperation,untime,modified_quantity,up_products,approve,modified_quantity,envelopes_id,sub_expense_money,sub_discounted_money,uniqueNumber,products_v2_spec,unique_status,is_product_choose')
            ->select();
        $envelopes_id          = $list[0]['envelopes_id'];
        $sub_expense_money     = 0;
        $sub_discounted_money  = 0;
        $uniqueNumberMoney     = 0;
        $increment             = 0;
        $productsuUniqueNumber = [];
        foreach ($list as $k => $item) {
            $capital              = db('visa_form')->where('find_in_set(:id,capital_id)', ['id' => $item['capital_id']])->whereNotNull('signing_time')->order('id asc')->select();
            $list[$k]['un_Price'] = round($item['un_Price'], 2);
            $list[$k]['to_price'] = round($item['to_price'], 2);
            if ($item['increment'] == 1) {
                $list[$k]['money'] = 1;
                //                $sub_expense_money    += $item['sub_expense_money'];
                //                $sub_discounted_money += $item['sub_discounted_money'];
            }
            if ($item['types'] == 2) {
                $list[$k]['money']    = 2;
                $list[$k]['to_price'] = '-' . $item['to_price'];
                $sub_expense_money    += $item['sub_expense_money'];
                $sub_discounted_money += $item['sub_discounted_money'];
            }
            if ($item['approve'] == 4) {
                $list[$k]['money']    = 2;
                $list[$k]['to_price'] = '-' . $item['to_price'];
                $sub_expense_money    += $item['sub_expense_money'];
                $sub_discounted_money += $item['sub_discounted_money'];
            }
            if ($item['approve'] == 5) {
                $list[$k]['un_Price'] = round($item['un_Price'], 2);
                $list[$k]['to_price'] = '-' . round(($item['square'] - $item['modified_quantity']) * $item['un_Price'], 2);
                $list[$k]['money']    = 2;
                $sub_expense_money    += round(($item['square'] - $item['modified_quantity']) / $item['square'] * $item['sub_expense_money'], 2);
                $sub_discounted_money += round(($item['square'] - $item['modified_quantity']) / $item['square'] * $item['sub_discounted_money'], 2);
            }
            if ($item['giveType'] == 2) {
                $list[$k]['giveType'] = 1;
                $list[$k]['to_price'] = 0;
            }
            if (isset($parem['id']) && !empty($parem['id']) && count($capital) > 1 && $capital[0]['id'] == $parem['id']) {
                $list[$k]['money'] = 1;
                //                $sub_expense_money    += $item['sub_expense_money'];
                //                $sub_discounted_money += $item['sub_discounted_money'];
            }

            if (isset($parem['id']) && !empty($parem['id']) && count($capital) > 1 && $capital[0]['id'] > $parem['id']) {
                $list[$k]['money']    = 2;
                $list[$k]['to_price'] = '-' . $item['to_price'];
                $sub_expense_money    += $item['sub_expense_money'];
                $sub_discounted_money += $item['sub_discounted_money'];
            }
            if (!empty($item['uniqueNumber'])) {
                $productsuUniqueNumber[] = $item['uniqueNumber'];
            }
        }


        $uniqueNumber = array_unique($productsuUniqueNumber);


        $envelopesProduct = \db('envelopes_product')->whereIn('uniqueNumber', $uniqueNumber)->where('envelopes_id', $envelopes_id)->select();

        $beLeftOver = empty($envelopesProduct) ? 0 : array_sum(array_column($envelopesProduct, 'beLeftOver'));

        $to_price = array_sum(array_column($list, 'to_price'));
        if ($to_price > 0) {
            $Additions = $to_price;
        } else {
            $Additions = $to_price;
        }
        r_date([
            'data' => $list,
            'allEndMoneyTitle' => "增项金额:" .
                round($Additions, 2) . "/n" .
                "增项主合同管理费:" . $mainMoney . "/n" .
                "增项代购合同管理费:" . $money . "/n" .
                "增项主合同优惠:" . $give_money . "/n" .
                "增项代购合同优惠:" . $purchasin_money . "/n" .
                "增项套餐一口价优惠:" . $beLeftOver . "/n" .
                "减项管理费退费:" . round($sub_expense_money, 2) . "/n" .
                "减项优惠价值扣减:" . round($sub_discounted_money, 2) . "/n" .
                "合计金额:" . round(round($Additions, 2) + $mainMoney + $money - $give_money - $purchasin_money + $sub_discounted_money - $sub_expense_money - $beLeftOver, 2)
        ], 200);
    }

    /*
     * 新签证单列表
     */
    public function newVisaList(Capital $capital)
    {
        $data = Request::instance()->post();
        if ($data['type'] == 1) {
            $visa_form       = db('visa_form')->where('order_id', $data['order_id'])->whereNUll('signing_time')->find();
            $mainMoney       = empty($visa_form['mainMoney']) ? 0 : $visa_form['mainMoney'];
            $give_money      = empty($visa_form['give_money']) ? 0 : $visa_form['give_money'];
            $purchasin_money = empty($visa_form['purchasin_money']) ? 0 : $visa_form['purchasin_money'];
            $money           = empty($visa_form['money']) ? 0 : $visa_form['money'];
            $id              = empty($visa_form['id']) ? 0 : $visa_form['id'];
            $duration        = empty($visa_form['duration']) ? 0 : $visa_form['duration'];
            $list            = $capital
                ->with('specsList')
                ->whereIn('capital_id', $visa_form['capital_id'])
                ->select();
        } else {
            $mainMoney       = 0;
            $give_money      = 0;
            $money           = 0;
            $id              = 0;
            $duration        = 0;
            $purchasin_money = 0;
            $list            = $capital
                ->with('specsList')
                ->where('ordesr_id', $data['order_id'])
                ->where(function ($quer) {
                    $quer->where('approve', 3)->whereOr('approve', 2);
                })->where('enable', 1)->where('types', 1)
                ->select();
        }
        $envelopes_id = 0;
        $envelopes_id = 0;
        foreach ($list as $k => $l) {
            //套餐总数量
            $envelopes_id                  = $l['envelopes_id'];
            if (!empty($l['uniqueNumber'])) {
                $list[$k]['uniqueNumberCount'] = \db('capital')->where('uniqueNumber', $l['uniqueNumber'])->where('enable', 1)->where('types', 1)->count();
                if ($data['type'] != 1) {
                    //提交的套餐数量
                    $list[$k]['uniqueNumberSubmitCount'] = \db('capital')->where('uniqueNumber', $l['uniqueNumber'])->where(function ($quer) {
                        $quer->where('approve', 3)->whereOr('approve', 2);
                    })->where('enable', 1)->where('types', 1)->count();
                } else {
                    //审核后的套餐数量
                    $list[$k]['uniqueNumberSubmitCount'] = \db('capital')->where('uniqueNumber', $l['uniqueNumber'])->where(function ($quer) {
                        $quer->where('approve', 4);
                    })->where('enable', 1)->where('types', 1)->count();
                }
            }
        }
        $listArray             = [];
        $sub_expense_money     = 0;
        $sub_discounted_money  = 0;
        $uniqueNumberMoney     = 0;
        $productsuUniqueNumber = [];

        foreach ($list as $k => $value) {
            $is_required_module = 1;
            if ($value['products_v2_spec'] != 0) {
                $is_required_module = $value['unique_status'];
            }
            if (empty($value['uniqueNumber']) || ($is_required_module == 0 && $value['uniqueNumberSubmitCount'] != $value['uniqueNumberCount'])) {
                $listArray[$k]['products']     = $value['products'];
                $listArray[$k]['uniqueNumber'] = $value['uniqueNumber'];
                $listArray[$k]['upProducts']   = $value['up_products'];
                if ($is_required_module == 0) {
                    $listArray[$k]['products']     = 0;
                    $listArray[$k]['uniqueNumber'] = 0;
                    $listArray[$k]['upProducts']   = 0;
                }
                $listArray[$k]['class_b']         = $value['class_b'];
                $listArray[$k]['capital_id']      = $value['capital_id'];
                $listArray[$k]['approve']         = $value['approve'];
                $listArray[$k]['approval_reason'] = $value['approval_reason'];
                $listArray[$k]['square']          = $value['square'];
                $listArray[$k]['company']         = $value['company'];
                $listArray[$k]['to_price']        = $value['to_price'];
                $listArray[$k]['un_Price']        = $value['un_Price'];
                if ($value['increment'] == 1 && $value['signed'] == 0 && $value['approve'] == 0) {
                    $listArray[$k]['increment'] = 1;
                } elseif ($value['modified_quantity'] == 0 && $value['approve'] != 0 && $value['signed'] == 0) {
                    $listArray[$k]['increment'] = 2;
                    $listArray[$k]['to_price']  = '-' . $value['to_price'];
                    $sub_expense_money          += $value['sub_expense_money'];
                    $sub_discounted_money       += $value['sub_discounted_money'];
                } elseif ($value['modified_quantity'] != 0 && $value['increment'] != 1 && $value['signed'] == 0) {
                    $listArray[$k]['increment'] = 2;
                    $listArray[$k]['square']    = bcsub($value['square'], $value['modified_quantity'], 2);
                    if ($value['increment_adopt'] != 0) {
                        $listArray[$k]['to_price'] = '-' . $value['to_price'];
                        $sub_expense_money         += $value['sub_expense_money'];
                        $sub_discounted_money      += $value['sub_discounted_money'];
                    } else {
                        $listArray[$k]['to_price'] = '-' . bcmul($listArray[$k]['square'], $value['un_Price'], 2);
                        $sub_expense_money         += bcmul(bcdiv(abs($listArray[$k]['to_price']), $value['to_price'], 2), $value['sub_expense_money'], 2);
                        $sub_discounted_money      += bcmul(bcdiv(abs($listArray[$k]['to_price']), $value['to_price'], 2), $value['sub_discounted_money'], 2);
                    }
                } elseif ($value['modified_quantity'] != 0 && $value['increment'] == 1 && $value['signed'] == 0) {
                    $listArray[$k]['increment'] = 2;
                    $listArray[$k]['square']    = bcsub($value['square'], $value['modified_quantity'], 2);
                    if ($value['increment_adopt'] != 0) {
                        $listArray[$k]['to_price'] = '-' . bcmul($listArray[$k]['square'], $value['un_Price'], 2);
                        $sub_expense_money         += bcmul(bcdiv(abs($listArray[$k]['to_price']), $value['to_price'], 2), $value['sub_expense_money'], 2);
                        $sub_discounted_money      += bcmul(bcdiv(abs($listArray[$k]['to_price']), $value['to_price'], 2), $value['sub_discounted_money'], 2);
                    }
                }
                if ($value['give'] == 2) {
                    $listArray[$k]['to_price'] = 0;
                }
                $approvedTime                  = \db('approval', config('database.zong'))
                    ->where('relation_id', $value['capital_id'])
                    ->where('city_id', config('cityId'))
                    ->order('approval.approval_id desc')
                    ->value('approved_time');
                $listArray[$k]['approvedTime'] = empty($approvedTime) ? '' : date('Y-m-d H:i:s', $approvedTime);
                $listArray[$k]['specsList']    = !empty($value['specs_list']) ? implode(array_column($value['specs_list'], 'option_value_title'), '/') : '';
                $uniqueNumberMoney             += $listArray[$k]['to_price'];
            } else {
                if ($value['increment'] == 1 && $value['signed'] == 0 && $value['approve'] == 0) {
                    $increment = 1;
                    //                    $sub_expense_money    += $value['sub_expense_money'];
                    //                    $sub_discounted_money += $value['sub_discounted_money'];
                } elseif ($value['approve'] != 0 && $value['signed'] == 0) {

                    $increment            = 2;
                    $sub_expense_money    += $value['sub_expense_money'];
                    $sub_discounted_money += $value['sub_discounted_money'];
                }
                $productsuUniqueNumber[] = $value['uniqueNumber'];
                $envelopes_id = $value['envelopes_id'];
            }
        }
        $listArray    = array_merge($listArray);
        $uniqueNumber = array_unique($productsuUniqueNumber);
        $titleArray   = [];
        if ($uniqueNumber) {
            $envelopesProduct = \db('envelopes_product')->whereIn('uniqueNumber', $uniqueNumber)->where('envelopes_id', $envelopes_id)->select();
            if (!empty($envelopesProduct)) {
                foreach ($envelopesProduct as $lis) {
                    $is_product_choose = \db('capital')->where('uniqueNumber', $lis['uniqueNumber'])->where('types', 1)->where('unique_status', 0)->where('is_product_choose', 1)->where('give', 0)->sum('to_price');
                    if ($lis['products_type'] == 1) {
                        $rows                = Db::connect(config('database.zong'))->table('products_spec')
                            ->field('products.*, products_spec.id as ids,products_spec.products_id,products_spec.products_spec_title,products_spec.products_spec_price,products_spec.products_spec_original_price,products_spec.products_spec_description,products_spec.discount_rate_1,products_spec.scheme_id,products_spec.discount_rate_2,products_spec.discount_rate_1,products.products_title')
                            ->join('products', 'products.id=products_spec.products_id', 'left')
                            ->where('products_spec.products_id', $lis['products_id'])
                            ->where('products_spec.scheme_id', $lis['schemeIds'])
                            ->find();
                        $products_spec_price = round($rows['products_spec_price'] / 100, 2);
                        $products_spec_title = $rows['products_spec_title'];
                        $products_title      = $rows['products_title'];
                        $products_id         = $rows['products_id'];
                        $ids                 = $rows['ids'];
                    } elseif ($lis['products_type'] == 2 && $lis['sales_method'] == 1) {
                        $rows_v2                     = Db::connect(config('database.zong'))->table('products_v2_spec')
                            ->field('products.*,products_v2_spec.*,products.id as ids')
                            ->join('products_v2 products', 'products.id=products_v2_spec.products_id', 'left')
                            ->where('products_v2_spec.products_id', $lis['products_id'])
                            ->where('products_v2_spec.is_required_module', 1)
                            ->select();
                        $envelopesProductCapitalList = [];
                        foreach ($listArray as $k => $item) {
                            if ($item['uniqueNumber'] == $lis['uniqueNumber']) {
                                $envelopesProductCapitalList[] = $item;
                            }
                        }
                        $products_spec_title = implode(array_unique(array_column($envelopesProductCapitalList, 'categoryName')), ",");
                        $products_spec_price = round(array_sum(array_column($rows_v2, 'products_spec_price')), 2) + $is_product_choose;
                        $products_title      = $rows_v2[0]['products_title'];
                        $products_id         = $rows_v2[0]['products_id'];
                        $ids                 = $products_id;
                    } elseif ($lis['sales_method'] == 2) {
                        $envelopesProductCapitalList = [];
                        foreach ($listArray as $k => $item) {
                            if ($item['uniqueNumber'] == $lis['uniqueNumber']) {
                                $envelopesProductCapitalList[] = $item;
                            }
                        }

                        $products_spec_title = implode(array_unique(array_column($envelopesProductCapitalList, 'categoryName')), ",");
                        $products_spec_price = round($lis['products_spec_price'], 2) + $is_product_choose;
                        $products_title      = $lis['title'];
                        $products_id         = $lis['schemeIds'];
                        $ids                 = $products_id;
                    }


                    $coutMainMoenyDiscount = 0;
                    $coutMoenyDiscount     = 0;
                    if ($lis['beLeftOver'] > 0) {
                        $coutMainMoenyDiscount = 0;
                        $coutMoenyDiscount     = 0;
                    }
                    $price = $products_spec_price;
                    if ($lis['approval'] == 2) {
                        $price = '-' . $price;
                    }
                    $beLeftOver         = $lis['beLeftOver'];
                    $moneySummation     = $lis['money'];
                    $IncreaseOrDecrease = 1;
                    $titleArray[]       = [
                        'title' => $products_title,
                        'products_id' => $products_id,
                        'productsSpecTitle' => $products_spec_title,
                        'price' => $price,
                        'uniqueNumber' => $lis['uniqueNumber'],
                        'money' => $moneySummation,
                        'IncreaseOrDecrease' => $IncreaseOrDecrease,
                        'coutMainMoenyDiscount' => $coutMainMoenyDiscount,
                        'coutMoenyDiscount' => $coutMoenyDiscount,
                        'only' => $ids,
                        'beLeftOver' => $beLeftOver,
                    ];
                }
            }
        }

        $buyItNowDiscount      = 0;
        $buyItNowDiscountPrice = empty($titleArray) ? 0 : array_sum(array_column($titleArray, 'price'));
        $orderList             = db('order')
            ->field('if(order_setting.visa_form_confirm=1,0,1) as shell,envelopes.envelopes_id')
            ->join('order_setting', 'order.order_id=order_setting.order_id', 'left')
            ->join('envelopes', 'order.order_id=envelopes.ordesr_id and envelopes.type =1', 'left')
            ->where('order.order_id', $data['order_id'])
            ->find();
        //        var_dump($uniqueNumberMoney , $buyItNowDiscountPrice , $mainMoney , $money , $give_money , $purchasin_money , $sub_discounted_money , $sub_expense_money);
        r_date(['data' => $listArray, 'mainMoney' => $mainMoney, 'give_money' => $give_money, 'purchasin_money' => $purchasin_money, 'money' => $money, 'duration' => $duration, 'total' => round($uniqueNumberMoney + $buyItNowDiscountPrice + $mainMoney + $money - $give_money - $purchasin_money + $sub_discounted_money - $sub_expense_money - $buyItNowDiscount, 2), 'Additions' => round($uniqueNumberMoney + $buyItNowDiscountPrice, 2), 'refundOfReducedManagementFee' => round($sub_expense_money, 2), 'deductionOfPreferentialValue' => round($sub_discounted_money, 2), 'id' => $id, 'envelopesId' => $orderList['envelopes_id'], 'products' => $titleArray, 'buyItNowDiscount' => '', 'shell' => $orderList['shell']], 200);
    }

    public function newVisaList1(Capital $capital)
    {
        try {
            $data = Request::instance()->post();

            // 数据初始化
            $visaForm = null;
            $mainMoney = $giveMoney = $purchasinMoney = $money = $id = $duration = $envelopesId = 0;

            // 根据type获取不同数据
            if ($data['type'] == 1) {
                $visaForm = db('visa_form')
                    ->where('order_id', $data['order_id'])
                    ->whereNull('signing_time')
                    ->find();

                $mainMoney = $visaForm['mainMoney'] ?? 0;
                $giveMoney = $visaForm['give_money'] ?? 0;
                $purchasinMoney = $visaForm['purchasin_money'] ?? 0;
                $money = $visaForm['money'] ?? 0;
                $id = $visaForm['id'] ?? 0;
                $duration = $visaForm['duration'] ?? 0;

                $list = $capital
                    ->with('specsList')
                    ->whereIn('capital_id', $visaForm['capital_id'])
                    ->select();
            } else {
                $list = $capital
                    ->with('specsList')
                    ->where('ordesr_id', $data['order_id'])
                    ->where(function ($query) {
                        $query->where('approve', 3)->whereOr('approve', 2);
                    })
                    ->where('enable', 1)
                    ->where('types', 1)
                    ->select();
            }

            // 计算套餐数量
            $this->calculatePackageCounts($list, $data['type']);

            // 处理列表数据
            $processedData = $this->processListData($list);
            $listArray = $processedData['listArray'];
            $subExpenseMoney = $processedData['subExpenseMoney'];
            $subDiscountedMoney = $processedData['subDiscountedMoney'];
            $productsuUniqueNumber = $processedData['productsuUniqueNumber'];
            $envelopesId = $processedData['envelopesId'];

            // 处理套餐数据
            $titleArray = $this->processPackageData($productsuUniqueNumber, $envelopesId, $listArray);

            // 获取订单信息
            $orderList = $this->getOrderInfo($data['order_id']);

            // 计算汇总数据
            $uniqueNumberMoney = array_sum(array_column($listArray, 'to_price'));
            $buyItNowDiscountPrice = empty($titleArray) ? 0 : array_sum(array_column($titleArray, 'price'));
            $buyItNowDiscount = 0;

            // 返回结果
            return r_date([
                'data' => $listArray,
                'mainMoney' => $mainMoney,
                'give_money' => $giveMoney,
                'purchasin_money' => $purchasinMoney,
                'money' => $money,
                'duration' => $duration,
                'total' => round($uniqueNumberMoney + $buyItNowDiscountPrice + $mainMoney + $money - $giveMoney - $purchasinMoney + $subDiscountedMoney - $subExpenseMoney - $buyItNowDiscount, 2),
                'Additions' => round($uniqueNumberMoney + $buyItNowDiscountPrice, 2),
                'refundOfReducedManagementFee' => round($subExpenseMoney, 2),
                'deductionOfPreferentialValue' => round($subDiscountedMoney, 2),
                'id' => $id,
                'envelopesId' => $orderList['envelopes_id'],
                'products' => $titleArray,
                'buyItNowDiscount' => '',
                'shell' => $orderList['shell']
            ], 200);
        } catch (\Exception $e) {
            // 记录异常日志
            \think\Log::error('newVisaList error: ' . $e->getMessage());
            return r_date(['error' => '系统错误，请稍后再试'], 500);
        }
    }

    /**
     * 计算套餐数量
     */
    private function calculatePackageCounts(&$list, $type)
    {
        foreach ($list as &$item) {
            if (!empty($item['uniqueNumber'])) {
                // 套餐总数量
                $item['uniqueNumberCount'] = \db('capital')
                    ->where('uniqueNumber', $item['uniqueNumber'])
                    ->where('enable', 1)
                    ->where('types', 1)
                    ->count();

                // 根据type不同计算不同的提交数量
                if ($type != 1) {
                    // 提交的套餐数量
                    $item['uniqueNumberSubmitCount'] = \db('capital')
                        ->where('uniqueNumber', $item['uniqueNumber'])
                        ->where(function ($query) {
                            $query->where('approve', 3)->whereOr('approve', 2);
                        })
                        ->where('enable', 1)
                        ->where('types', 1)
                        ->count();
                } else {
                    // 审核后的套餐数量
                    $item['uniqueNumberSubmitCount'] = \db('capital')
                        ->where('uniqueNumber', $item['uniqueNumber'])
                        ->where('approve', 4)
                        ->where('enable', 1)
                        ->where('types', 1)
                        ->count();
                }
            }
        }
    }

    /**
     * 处理列表数据
     */
    private function processListData($list)
    {
        $listArray = [];
        $subExpenseMoney = 0;
        $subDiscountedMoney = 0;
        $productsuUniqueNumber = [];
        $envelopesId = 0;

        foreach ($list as $key => $value) {
            $isRequiredModule = $value['products_v2_spec'] != 0 ? $value['unique_status'] : 1;

            // 处理无套餐或未选满的情况
            if (empty($value['uniqueNumber']) || ($isRequiredModule == 0 && $value['uniqueNumberSubmitCount'] != $value['uniqueNumberCount'])) {
                $item = [
                    'products' => $value['products'],
                    'uniqueNumber' => $value['uniqueNumber'],
                    'upProducts' => $value['up_products'],
                    'class_b' => $value['class_b'],
                    'capital_id' => $value['capital_id'],
                    'approve' => $value['approve'],
                    'approval_reason' => $value['approval_reason'],
                    'square' => $value['square'],
                    'company' => $value['company'],
                    'to_price' => $value['to_price'],
                    'un_Price' => $value['un_Price'],
                    'increment' => 0,
                    'approvedTime' => '',
                    'specsList' => !empty($value['specs_list']) ? implode(array_column($value['specs_list'], 'option_value_title'), '/') : ''
                ];

                // 如果是必填模块但未选满，则设为0
                if ($isRequiredModule == 0) {
                    $item['products'] = $item['uniqueNumber'] = $item['upProducts'] = 0;
                }

                // 处理增量状态
                if ($value['increment'] == 1 && $value['signed'] == 0 && $value['approve'] == 0) {
                    $item['increment'] = 1;
                } elseif (($value['modified_quantity'] == 0 && $value['approve'] != 0 && $value['signed'] == 0) ||
                    ($value['modified_quantity'] != 0 && $value['increment'] != 1 && $value['signed'] == 0)
                ) {
                    $item['increment'] = 2;
                    $item['to_price'] = '-' . $value['to_price'];
                    $subExpenseMoney += $value['sub_expense_money'];
                    $subDiscountedMoney += $value['sub_discounted_money'];
                } elseif ($value['modified_quantity'] != 0 && $value['increment'] == 1 && $value['signed'] == 0) {
                    $item['increment'] = 2;
                    $item['square'] = bcsub($value['square'], $value['modified_quantity'], 2);

                    if ($value['increment_adopt'] != 0) {
                        $item['to_price'] = '-' . bcmul($item['square'], $value['un_Price'], 2);
                        $subExpenseMoney += bcmul(bcdiv(abs($item['to_price']), $value['to_price'], 2), $value['sub_expense_money'], 2);
                        $subDiscountedMoney += bcmul(bcdiv(abs($item['to_price']), $value['to_price'], 2), $value['sub_discounted_money'], 2);
                    }
                }

                // 赠品处理
                if ($value['give'] == 2) {
                    $item['to_price'] = 0;
                }

                // 获取审批时间
                $approvedTime = \db('approval', config('database.zong'))
                    ->where('relation_id', $value['capital_id'])
                    ->where('city_id', config('cityId'))
                    ->order('approval.approval_id desc')
                    ->value('approved_time');

                $item['approvedTime'] = empty($approvedTime) ? '' : date('Y-m-d H:i:s', $approvedTime);

                $listArray[$key] = $item;
            } else {
                // 处理完整套餐
                if ($value['increment'] == 1 && $value['signed'] == 0 && $value['approve'] == 0) {
                    $increment = 1;
                } elseif ($value['approve'] != 0 && $value['signed'] == 0) {
                    $increment = 2;
                    $subExpenseMoney += $value['sub_expense_money'];
                    $subDiscountedMoney += $value['sub_discounted_money'];
                }

                $productsuUniqueNumber[] = $value['uniqueNumber'];
                $envelopesId = $value['envelopes_id'];
            }
        }

        return [
            'listArray' => array_merge($listArray),
            'subExpenseMoney' => $subExpenseMoney,
            'subDiscountedMoney' => $subDiscountedMoney,
            'productsuUniqueNumber' => array_unique($productsuUniqueNumber),
            'envelopesId' => $envelopesId
        ];
    }

    /**
     * 处理套餐数据
     */
    private function processPackageData($uniqueNumbers, $envelopesId, $listArray)
    {
        $titleArray = [];

        if (empty($uniqueNumbers)) {
            return $titleArray;
        }

        $envelopesProducts = \db('envelopes_product')
            ->whereIn('uniqueNumber', $uniqueNumbers)
            ->where('envelopes_id', $envelopesId)
            ->select();

        foreach ($envelopesProducts as $product) {
            $isProductChoose = \db('capital')
                ->where('uniqueNumber', $product['uniqueNumber'])
                ->where('types', 1)
                ->where('unique_status', 0)
                ->where('is_product_choose', 1)
                ->where('give', 0)
                ->sum('to_price');

            $productsSpecTitle = '';
            $productsSpecPrice = 0;
            $productsTitle = '';
            $productsId = 0;
            $ids = 0;

            if ($product['products_type'] == 1) {
                // 处理产品类型1
                $rows = Db::connect(config('database.zong'))->table('products_spec')
                    ->field('products.*, products_spec.id as ids,products_spec.products_id,products_spec.products_spec_title,products_spec.products_spec_price,products_spec.products_spec_original_price,products_spec.products_spec_description,products_spec.discount_rate_1,products_spec.scheme_id,products_spec.discount_rate_2,products_spec.discount_rate_1,products.products_title')
                    ->join('products', 'products.id=products_spec.products_id', 'left')
                    ->where('products_spec.products_id', $product['products_id'])
                    ->where('products_spec.scheme_id', $product['schemeIds'])
                    ->find();

                $productsSpecPrice = round($rows['products_spec_price'] / 100, 2);
                $productsSpecTitle = $rows['products_spec_title'];
                $productsTitle = $rows['products_title'];
                $productsId = $rows['products_id'];
                $ids = $rows['ids'];
            } elseif ($product['products_type'] == 2 && $product['sales_method'] == 1) {
                // 处理产品类型2且销售方式1
                $rowsV2 = Db::connect(config('database.zong'))->table('products_v2_spec')
                    ->field('products.*,products_v2_spec.*,products.id as ids')
                    ->join('products_v2 products', 'products.id=products_v2_spec.products_id', 'left')
                    ->where('products_v2_spec.products_id', $product['products_id'])
                    ->where('products_v2_spec.is_required_module', 1)
                    ->select();

                $envelopesProductCapitalList = [];
                foreach ($listArray as $item) {
                    if ($item['uniqueNumber'] == $product['uniqueNumber']) {
                        $envelopesProductCapitalList[] = $item;
                    }
                }

                $productsSpecTitle = implode(array_unique(array_column($envelopesProductCapitalList, 'categoryName')), ",");
                $productsSpecPrice = round(array_sum(array_column($rowsV2, 'products_spec_price')), 2) + $isProductChoose;
                $productsTitle = $rowsV2[0]['products_title'];
                $productsId = $rowsV2[0]['products_id'];
                $ids = $productsId;
            } elseif ($product['sales_method'] == 2) {
                // 处理销售方式2
                $envelopesProductCapitalList = [];
                foreach ($listArray as $item) {
                    if ($item['uniqueNumber'] == $product['uniqueNumber']) {
                        $envelopesProductCapitalList[] = $item;
                    }
                }

                $productsSpecTitle = implode(array_unique(array_column($envelopesProductCapitalList, 'categoryName')), ",");
                $productsSpecPrice = round($product['products_spec_price'], 2) + $isProductChoose;
                $productsTitle = $product['title'];
                $productsId = $product['schemeIds'];
                $ids = $productsId;
            }

            // 计算折扣
            $coutMainMoenyDiscount = $coutMoenyDiscount = 0;
            if ($product['beLeftOver'] > 0) {
                $coutMainMoenyDiscount = $coutMoenyDiscount = 0;
            }

            // 设置价格
            $price = $productsSpecPrice;
            if ($product['approval'] == 2) {
                $price = '-' . $price;
            }

            // 添加到结果数组
            $titleArray[] = [
                'title' => $productsTitle,
                'products_id' => $productsId,
                'productsSpecTitle' => $productsSpecTitle,
                'price' => $price,
                'uniqueNumber' => $product['uniqueNumber'],
                'money' => $product['money'],
                'IncreaseOrDecrease' => 1,
                'coutMainMoenyDiscount' => $coutMainMoenyDiscount,
                'coutMoenyDiscount' => $coutMoenyDiscount,
                'only' => $ids,
                'beLeftOver' => $product['beLeftOver']
            ];
        }

        return $titleArray;
    }

    /**
     * 获取订单信息
     */
    private function getOrderInfo($orderId)
    {
        return db('order')
            ->field('if(order_setting.visa_form_confirm=1,0,1) as shell,envelopes.envelopes_id')
            ->join('order_setting', 'order.order_id=order_setting.order_id', 'left')
            ->join('envelopes', 'order.order_id=envelopes.ordesr_id and envelopes.type =1', 'left')
            ->where('order.order_id', $orderId)
            ->find();
    }
    /*
     * 删除增项清单清单
     */
    public function deleteList(Common $common)
    {
        $data      = Request::instance()->get();
        $visa_form = db('visa_form')->where('order_id', $data['order_id'])->whereNUll('signing_time')->find();
        if (!empty($visa_form['autograph'])) {
            r_date(null, 300, "用户已签字无法删除");
        }
        $capital = db('capital')->where('capital_id', $data['capital_id'])->find();
        if (empty($visa_form)) {
            if (($capital['increment'] == 0 && $capital['approve'] == 1) || ($capital['increment'] == 1 && $capital['signed'] == 1) || ($capital['increment'] == 1 && $capital['approve'] == 1)) {
                r_date(null, 300, "用户已签字无法删除");
            }
        }

        $capital_id = explode(',', $visa_form['capital_id']);
        foreach ($capital_id as $k => $item) {
            if ($item == $data['capital_id']) {
                unset($capital_id[$k]);
            }
        }
        $capitalCout = db('visa_form')->where('find_in_set(:id,capital_id)', ['id' => $data['capital_id']])->where('id', $visa_form['id'])->select();
        if (count($capitalCout) != 0) {
            if (empty(array_merge($capital_id))) {
                db('visa_form')->where('id', $visa_form['id'])->delete();
            } else {
                if ($capital['agency'] == 1) {
                    $visaPurchasinMoney = 0;
                    $visaMoney          = 0;
                    if ($visa_form['purchasin_money'] != 0) {
                        $visaPurchasinMoney = $visa_form['purchasin_money'] - $capital['sub_discounted_money'];
                    }
                    if ($visa_form['money'] != 0) {
                        $visaMoney = $visa_form['money'] - $capital['sub_expense_money'];
                    }
                    $list = ['capital_id' => implode(',', array_merge($capital_id)), 'purchasin_money' => $visaPurchasinMoney, 'money' => $visaMoney];
                    if ($capital['increment'] == 0) {
                        unset($list['purchasin_money']);
                    }
                } else {
                    $visaMainMoney = 0;
                    $visaGiveMoney = 0;
                    if ($visa_form['mainMoney'] != 0) {
                        $visaMainMoney = $visa_form['mainMoney'] - $capital['sub_expense_money'];
                    }
                    if ($visa_form['give_money'] != 0) {
                        $visaGiveMoney = $visa_form['give_money'] - $capital['sub_discounted_money'];
                    }
                    $list = ['capital_id' => implode(',', array_merge($capital_id)), 'give_money' => $visaGiveMoney, 'mainMoney' => $visaMainMoney];
                    if ($capital['increment'] == 0) {
                        unset($list['give_money']);
                    }
                }
                db('visa_form')->where('id', $visa_form['id'])->update($list);
            }
        }
        if ($capital['modified_quantity'] == 0 && $capital['approve'] != 0) {
            $type = 6;
        } elseif ($capital['modified_quantity'] != 0 && $capital['approve'] != 0) {
            $type = 8;
        } elseif ($capital['increment'] == 1 && $capital['approve'] == 0) {
            $type = 9;
        }
        $order_setting = db('order_setting')->where('order_id', $data['order_id'])->find();
        if ($type == 6 || $type == 8) {
            db('capital')->where('capital_id', $data['capital_id'])->update(['approve' => 0, 'approval_reason' => '申请人撤销审批' . date('Y-m-d H:i:s', time()), 'modified_quantity' => 0, 'signed' => 1]);
        } else if ($type == 9) {
            db('capital')->where('capital_id', $data['capital_id'])->update(['approve' => 0, 'enable' => 0, 'approval_reason' => '申请人撤销审批' . date('Y-m-d H:i:s', time()), 'modified_quantity' => 0, 'signed' => 1]);
            if (!empty($capital['uniqueNumber'])) {
                db('capital')->where('capital_id', $data['capital_id'])->update(['up_products_time' => time(), 'up_products' => 1]);
                $Capital = new Capital();
                $Capital->assemblyAdditions(implode(',', array_merge($capital_id)), $visa_form['give_money'] - $capital['sub_discounted_money'], $visa_form['purchasin_money'] - $capital['sub_discounted_money'], $order_setting, 0, 0,1);
            }
            db('auxiliary_project_list')->where('capital_id', $data['capital_id'])->update(['delete_time' => time()]);
        }
        Db::connect(config('database.db2'))->table('agency_task')->where('capital_id', $data['capital_id'])->update(['status' => 0]);
        $approval_bef = db('approval_bef', config('database.zong'))->order('id desc')->where('approval_id',  $data['capital_id'])->find();
        db('approval_bef', config('database.zong'))->where('approval_id',  $data['capital_id'])->where('state', 0)->update(['state' => 1]);
        if (!empty($approval_bef['extended_info']) && $approval_bef['extended_info'] != '') {
            db('approval_record', config('database.zong'))->where('id',  $approval_bef['extended_info'])->update(['status' => 2]);
        }

        $approval = db('approval', config('database.zong'))->where('relation_id', $data['capital_id'])->where('city_id', config('cityId'))->where('type', $type)->order('approval_id desc')->find();
        if ($approval['status'] == 0) {
            db('approval', config('database.zong'))->where('approval_id', $approval['approval_id'])->update(['status' => 1]);
            db('approval_schedule', config('database.zong'))->where('approval_id', $approval['approval_id'])->update(['approval_status' => 2, 'remarks' => '申请人撤销审批']);
        }
        if ($type == 6) {
            db('capital_minus_beforehand')->where(['minus_id' => $data['capital_id']])->where('delete_time', 0)->update(['delete_time' => time()]);
            $common->deleteRecalculatedCreditLimit($data['order_id'], $data['capital_id']);
        }

        r_date(null, 200);
    }

    public function productsDelete(Common $common)
    {

        $data = Request::instance()->get();
        db()->startTrans();
        try {
            $visa_form = db('visa_form')->where('order_id', $data['orderId'])->whereNUll('signing_time')->find();
            if (!empty($visa_form['autograph'])) {
                r_date(null, 300, "用户已签字无法删除");
            }
            $capital       = db('capital')->where('uniqueNumber', $data['uniqueNumber'])->select();
            $zhuGuanLiFei = 0;
            $zhuYouHui = 0;
            $daiGuanLiFei = 0;
            $daiYouHui = 0;
            foreach ($capital as $item) {
                if ($item['agency'] == 1) {
                    $daiGuanLiFei += $item['sub_expense_money'];
                    $daiYouHui += $item['sub_discounted_money'];
                }
                if ($item['agency'] == 0) {
                    $zhuGuanLiFei += $item['sub_expense_money'];
                    $zhuYouHui += $item['sub_discounted_money'];
                }
            }
            $envelopes_product       = db('envelopes_product')->where('uniqueNumber', $data['uniqueNumber'])->find();
            $capital_id    = explode(',', $visa_form['capital_id']);
            $capitalIdList = array_column($capital, 'capital_id');
            if (empty($visa_form)) {
                $visa_formList = db('visa_form')->where('capital_id', implode(",", $capitalIdList))->where('order_id', $data['orderId'])->order('id desc')->find();
                if (!empty($visa_formList) && !empty($visa_formList['signing_time'])) {
                    r_date(null, 300, "用户已签字无法删除");
                }
            }
            foreach ($capital_id as $k => $item) {
                foreach ($capitalIdList as $value) {
                    if ($item == $value) {
                        unset($capital_id[$k]);
                    }
                }
            }

            if ($capital[0]['modified_quantity'] == 0 && $capital[0]['approve'] != 0) {
                $type = 6;
            } elseif ($capital[0]['modified_quantity'] != 0 && $capital[0]['approve'] != 0) {
                $type = 8;
            } elseif ($capital[0]['increment'] == 1 && $capital[0]['approve'] == 0) {
                $type = 9;
            }
            if (empty(array_merge($capital_id))) {
                db('visa_form')->where('id', $visa_form['id'])->delete();
            } else {
                if ($type == 6 || $type == 8) {
                    $list = ['capital_id' => implode(',', array_merge($capital_id))];
                } elseif ($type == 9) {
                    $visaMainMoney = 0;
                    $giveMoney     = 0;
                    $products_main_discount_money = 0;
                    $products_purchasing_discount_money = 0;
                    $purchasin_money = 0;
                    $money = 0;
                    if ($visa_form['mainMoney'] > 0) {
                        $visaMainMoney = $visa_form['mainMoney'] - $zhuGuanLiFei;
                    }
                    if ($visa_form['give_money'] > 0) {
                        $giveMoney = $visa_form['give_money'] - $zhuYouHui;
                    }
                    if ($visa_form['money'] > 0) {
                        $money = $visa_form['money'] - $daiGuanLiFei;
                    }
                    if ($visa_form['purchasin_money'] > 0) {
                        $purchasin_money = $visa_form['purchasin_money'] - $daiYouHui;
                    }
                    if ($visa_form['products_main_discount_money'] > 0) {
                        $products_main_discount_money = $visa_form['products_main_discount_money'] - $envelopes_product['products_main_discount_money'];
                    }
                    if ($visa_form['products_purchasing_discount_money'] > 0) {
                        $products_purchasing_discount_money = $visa_form['products_purchasing_discount_money'] - $envelopes_product['products_purchasing_discount_money'];
                    }
                    $list = [
                        'capital_id' => implode(',', array_merge($capital_id)),
                        'give_money' => $giveMoney,
                        'mainMoney' => $visaMainMoney,
                        'money' => $money,
                        'purchasin_money' => $purchasin_money,
                        'products_main_discount_money' => $products_main_discount_money,
                        'products_purchasing_discount_money' => $products_purchasing_discount_money
                    ];
                }
                db('visa_form')->where('id', $visa_form['id'])->update($list);
            }
            if ($type == 6 || $type == 8) {
                db('capital')->where('uniqueNumber', $data['uniqueNumber'])->update(['approve' => 0, 'approval_reason' => '申请人撤销审批' . date('Y-m-d H:i:s', time()), 'modified_quantity' => 0, 'signed' => 1]);
                db('envelopes_product')->where('uniqueNumber', $data['uniqueNumber'])->update(['approval' => 0]);
            } else if ($type == 9) {
                db('capital')->where('uniqueNumber', $data['uniqueNumber'])->update(['approve' => 0, 'enable' => 0, 'approval_reason' => '申请人撤销审批' . date('Y-m-d H:i:s', time()), 'modified_quantity' => 0, 'signed' => 1]);
                if (!empty($capital['uniqueNumber'])) {
                    db('capital')->where('uniqueNumber', $data['uniqueNumber'])->update(['up_products_time' => time(), 'up_products' => 1]);
                }
                db('auxiliary_project_list')->whereIn('capital_id', $capitalIdList)->update(['delete_time' => time()]);
            }
            db('approval_bef', config('database.zong'))->where('approval_id',  $data['uniqueNumber'])->where('state', 0)->update(['state' => 1]);
            $approval = db('approval', config('database.zong'))->where('relation_id', $data['uniqueNumber'])->where('city_id', config('cityId'))->where('type', 10)->order('approval_id desc')->find();
            if ($approval['status'] == 0) {
                db('approval', config('database.zong'))->where('approval_id', $approval['approval_id'])->update(['status' => 1]);
                db('approval_schedule', config('database.zong'))->where('approval_id', $approval['approval_id'])->update(['approval_status' => 2, 'remarks' => '申请人撤销审批']);
            }
            if ($type == 6) {
                $approval_bef = db('approval_bef', config('database.zong'))->order('id desc')->where('approval_id',  $data['uniqueNumber'])->find();
                if (!empty($approval_bef['extended_info']) && $approval_bef['extended_info'] != '') {
                    db('approval_record', config('database.zong'))->whereIn('id',  $approval_bef['extended_info'])->update(['status' => 2]);
                }
                db('capital_minus_beforehand')->whereIn('minus_id', $capitalIdList)->where('delete_time', 0)->update(['delete_time' => time()]);
                $common->deleteRecalculatedCreditLimit($data['orderId'], 0, 0, 3, $data['uniqueNumber']);
            }

            db()->commit();

            r_date(null, 200);
        } catch (\Exception $e) {
            db()->rollback();
            r_date(null, 300, $e->getMessage());
        }
    }


    /*
     * 重新提交清单
     */
    public
    function visaResubmit(Approval $approval, Capital $capital)
    {
        $data        = Request::instance()->get();
        $capitalFind = $capital->QueryOne($data['capital_id']);
        $user        = Db::table('order')
            ->join('user', 'user.user_id=order.assignor', 'left')
            ->where('order.order_id', $capitalFind['ordesr_id'])
            ->find();
        if (isset($capitalFind['quantity']) && $capitalFind['quantity'] != 0) {
            $title        = $capitalFind['class_b'] . '减少方量到(' . $data['quantity'] . ')';
            $approvalType = 9;
        } else {
            $title        = $capitalFind['class_b'] . '项目减项(' . $user['username'] . ')';
            $approvalType = 6;
        }
        db('capital')->where('capital_id', $data['capital_id'])->update(['approve' => 3, 'signed' => 0]);
        $approval->Reimbursement($data['capital_id'], $title, $user['username'], $approvalType);
        r_date(null, 200);
    }

    /*
     * 分享清单
     */
    public
    function share()
    {
        $data      = Request::instance()->get();
        $visa_form = db('visa_form')->where('id', $data['id'])->update(['share' => 1]);
        r_date(null, 200);
    }

    /**
     * 二维数组根据某个字段排序
     * @param array $array 要排序的数组
     * @param string $keys 要排序的键字段
     * @param string $sort 排序类型  SORT_ASC     SORT_DESC
     * @return array 排序后的数组
     */
    function arraySort($array, $keys, $sort = SORT_DESC)
    {
        $keysValue = [];
        foreach ($array as $k => $v) {
            $keysValue[$k] = $v[$keys];
        }
        array_multisort($keysValue, $sort, $array);
        return $array;
    }

    /*
     * 签字确认
     */
    public function SignatureConfirmation()
    {
        $data = Authority::param(['orderId', 'id']);
        if ($data['id'] == 0) {
            r_date(null, 300, '请操作增减项后确认！');
        }
        db('visa_form')->where('id', $data['id'])->update(['share' => 1, 'autograph' => 1]);
        $list = SignatureConfirmation($data['orderId'], $data['id']);
        $list = json_decode($list, true);
        if ($list['errcode'] == 200) {
            r_date(null, 200);
        }
        r_date(null, 300, $list['msg']);
    }
}
